import {
  defaultOptions,
  controlSuffix,
  viewSuffix,
  EVENT_CONFIG_MSG,
  EVENT_INTI_CONFIG,
  topicMsg,
  topicState,
  TOPIC_SUFFIX,
  EVETN_CONTROL_CONFIG_MSG,
  EVENT_SCREEN_TO_CONFG,
  topicScreen,
  topicLeave,
  EVENT_LEAVE_PAGE,
  topicEnter,
  EVENT_ENTER_PAGE,
} from "../constant";
import { event } from "./event";
import config from "../../../config";
import { storage, getScreenInfo, debound } from "./utils";

export default class Strategy {
  /**
   * 当前有多少个用户登录
   */
  usernames = new Map();

  data = {
    publish: {
      topic: "sgb",
      qos: 0,
    },
    // 订阅主题
    subscription: {
      topic: "sgb",
      qos: 0,
    },
  };

  /**
   * 已经在初始化的时候发送过屏幕配置的用户
   */
  firsetSendScreenOptionsUsername = [];

  constructor(id, options) {
    this.handlers = {};
    this.id = id;
    this.options = { ...defaultOptions, ...options };
    this.topicMsg = topicMsg(this.id); // `sgb/${this.id}/config`;
    this.topicState = topicState(this.id);
    this.topicScreen = topicScreen(this.id);
    this.topicLeave = topicLeave(this.id);
    this.topicEnter = topicEnter(this.id);
    this.username = `${TOPIC_SUFFIX}_${+new Date()}_${this.options.isControl ? controlSuffix : viewSuffix}`;
  }

  on(eventType, callback) {
    if (eventType in this.handlers) {
      this.handlers[eventType].add(callback);
    } else {
      const set = new Set();
      set.add(callback);
      this.handlers[eventType] = set;
    }
  }
  dispatch(eventType, ...payload) {
    const handlers = this.handlers[eventType] || [];
    handlers.forEach((hand) => {
      hand(...payload);
    });
  }

  pushUserName({ isControl, username }) {
    this.usernames.set(username, { isControl });
    this.dispatchEnter(username);
    return true;
  }

  popUserName(usernaem) {
    this.usernames.delete(usernaem);
  }

  includesUserName(username) {
    return !!this.usernames.get(username);
  }

  getUsernameByName(username) {
    return this.usernames.get(username);
  }

  dispatchEnter(payload) {
    this.dispatch(EVENT_ENTER_PAGE, payload, this.getNamesToArray());
  }

  dispatchLevae(username) {
    this.popUserName(username);

    this.dispatch(EVENT_LEAVE_PAGE, username, this.getNamesToArray());
  }

  getNamesToArray() {
    const arr = [];
    this.usernames.forEach((value, key) => {
      arr.push({ username: key, isControl: value.isControl });
    });

    return arr;
  }

  payloadWrap(payload = {}) {
    return JSON.stringify({
      id: this.id,
      isControl: this.options.isControl,
      time: Date.now(),
      username: this.username,
      ...payload,
    });
  }
}
